package com.iweb.controller;

import cn.hutool.jwt.JWT;
import com.iweb.commons.ResultEntity;
import com.iweb.model.Game;
import com.iweb.model.OrderG;
import com.iweb.model.User;
import com.iweb.service.UserService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Time :2022/8/15 14:01
 * Author : kriller
 * Project : steam-malls
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Resource
    private UserService userService;

    //登录
    @PostMapping("login")
    public ResultEntity<User> login(@RequestBody User user, HttpServletResponse resp){
        User userData = userService.findByAccount(user.getUserAccount());
        if (userData == null) {
            return new ResultEntity<>(3001, "用户不存在", false, null);
        }
        if (!userData.getUserPwd().equals(user.getUserPwd())) {
            return new ResultEntity<>(3002, "密码不正确", false, null);
        }
        if(userData.getUserState() == 0){
            return new ResultEntity<>(3003, "账号被封禁", false, null);
        }
        // TOKEN  JWT = json web token
        byte[] key = "iweb".getBytes(); // 不能给人知道
        String token = JWT.create()
                .setPayload("sub", "user")
                .setPayload("userAccount", userData.getUserAccount())
                .setPayload("userId", userData.getUserId())
                .setPayload("userName",userData.getUserName())
                .setKey(key).sign();
        // session 是通过 cookie 响应的 , 写到响应头
        resp.setHeader("Access-control-expose-headers", "token");
        resp.addHeader("token", token);
        // eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIiwiYWNjb3VudCI6ImFkbWluIiwidXNlcklkIjoxfQ.cFoYNXqwVMJzQS7TdYZPURIWyvUMhyZLV65Y4NvJ2yQ
        return new ResultEntity<>(2000, "登录成功", true, null);

    }
    //注册
    @PostMapping("register")
    public ResultEntity<User> register(@RequestBody User user){
        User account = userService.findByAccount(user.getUserAccount());
        if (account!=null){
            return new ResultEntity<>(3001,"该账号已注册",false,null);
        }
        if (user.getUserPhone()==null){
            user.setUserPhone(user.getUserAccount());
        }
        if (user.getUserName()==null){
            user.setUserName(user.getUserAccount());
        }
        if (user.getUserSex()==null){
            user.setUserSex("保密");
        }
        user.setUserState(1);
        userService.insertUser(user);
        return new ResultEntity<>(2000,"注册成功",true,null);
    }
    //获取用户信息
    @GetMapping("info")
    public ResultEntity<User> userIfo(){
//        Integer userId = getUserId();
        Integer userId = 1;
        User user = userService.findUserById(userId);
        return new ResultEntity<>(2000,"获取用户信息",true,user);
    }
    //根据token获取用户id
    private Integer getUserId() {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        String token = request.getHeader("token");
        return Integer.parseInt(JWT.of(token).getPayload("userId").toString());
    }
    //添加愿望单
    @PostMapping("wish_add")
    public ResultEntity<Game> addWish(@RequestParam Integer gameId){
//        Integer userId = getUserId();
        Integer userId = 1 ;
        Integer wishId = userService.findWishByUGId(userId,gameId);
        if (wishId==null)
        {
            userService.insertWish(userId,gameId);
            return new ResultEntity<>(2000,"增加愿望单",true,null);
        }else{
            return new ResultEntity<>(3001,"已添加到愿望单",false,null);
        }

    }
    //获取愿望单内的游戏列表
    @GetMapping("wish")
    public ResultEntity<List<Game>> getUserWish(){
//        Integer userId = getUserId();
        Integer userId = 1;
        List<Game> games = userService.getWishList(userId);
        return new ResultEntity<>(2000,"获取愿望单",true,games);
    }
    //删除愿望单
    @PostMapping("wish_delete")
    public ResultEntity<Game> deleteWish(@RequestParam Integer gameId){
        //Integer userId = getUserId();
        Integer userId = 1;
        userService.deleteByUserIdAndGameId(userId,gameId);
        return new ResultEntity<>(2000,"删除愿望单中的游戏成功",true,null);
    }
    //获取游戏库, 即订单中状态为已支付的游戏列表
    @GetMapping("user_game")
    public ResultEntity<List<OrderG>> getUserGame(){
//        Integer userId = getUserId();
        Integer userId = 1;
        List<OrderG> games = userService.getUserGame(userId);
        for (OrderG orderG : games) {
            orderG.setOrderGIdString(orderG.getOrderGId().toString());
            System.out.println(orderG.getOrderGIdString());
        }
        System.out.println(1);
        return new ResultEntity<>(2000,"获取游戏库",true,games);
    }
    //用户修改用户属性
    @PostMapping("modify")
    public  ResultEntity<User> modifyUser(@RequestBody User user){
//        Integer userId = getUserId();
        Integer userId = 1;
        user.setUserId(userId);
        if (user.getUserPhone()!=null){
            user.setUserAccount(user.getUserPhone());
        }
        userService.updateUser(user);
        return new ResultEntity<>(2000,"修改用户信息",true,null);
    }
    //管理员: 列出所有用户, 提供页码
    //由前端实现分页, page参数舍弃
    @GetMapping("list_user")
   // public ResultEntity<List<User>> listAllUserByPage(@RequestParam Integer page){
    public ResultEntity<List<User>> listAllUserByPage(){
        List<User> users = userService.listUserBypage();
        return  new ResultEntity<>(2000,"管理员按页获取用户:",true,users);
    }
    //管理员更改用户状态
    @PostMapping("modify_userState")
    public ResultEntity<User>  modifyUserState(@RequestBody User user){
        userService.updateUserState(user);
        return new ResultEntity<>(2000,"管理员修改用户状态",true,null);
    }
}
